//
//  LandscapeViewController.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/11/12.
//

#import "LandscapeViewController.h"
/**二维码*/
#import "SGQRCode.h"
#import "QRCodeViewController.h"
#import "LandscapeLiveVC.h"
#import "CustomQualityView.h"
@interface LandscapeViewController ()<QRCodeDelegate,CustomQualityDelegate,LandscapeLivewDelegate>
{
    NSInteger selectedIndex;
    NSString *rtmpStr;
    
    NSInteger _videoW;
    NSInteger _videoH;
    NSInteger _videoKb;
}
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UITextField *urlText;
@property(nonatomic,copy)NSString *rtmpStr;
@property(nonatomic,strong)UISegmentedControl *segmentedControl;
@property(nonatomic,assign)BOOL isLiveStoped;//是否直播结束了，
@end

@implementation LandscapeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:false animated:true];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:true animated:true];
}
- (void)goBackToPreview{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    selectedIndex = 2;
    self.isLiveStoped = false;
    self.rtmpStr = @"";
    _videoH = 0;
    _videoW = 0;
    _videoKb = 0;
    // Do any additional setup after loading the view.
    
    UIButton *buttonBack=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonBack.frame =  CGRectMake(0, 0, 50, 50);
    [buttonBack setImage:[UIImage imageNamed:@"nav-return"] forState:UIControlStateNormal];
    [buttonBack addTarget:self action:@selector(goBackToPreview) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:buttonBack];
    buttonBack.imageEdgeInsets = UIEdgeInsetsMake(0, -27, 0, 0);
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.view.backgroundColor =  [UIColor colorWithRed:246/255.0 green:247/255.0 blue:251/255.0 alpha:1.0];
    self.title = @"横屏直播";
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        [appearance configureWithOpaqueBackground];
        //设置导航条背景色
        appearance.backgroundColor = UIColor.whiteColor;
        //设置导航条标题颜色
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setValue:UIColor.blackColor forKey:NSForegroundColorAttributeName];
        appearance.titleTextAttributes = attributes;
        
        [UINavigationBar appearance].standardAppearance = appearance;
        [UINavigationBar appearance].scrollEdgeAppearance = appearance;
    } else {
        // Fallback on earlier versions
    }
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:self.scrollView];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
       //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
       tapGestureRecognizer.cancelsTouchesInView = NO;
       //将触摸事件添加到当前view
       [self.view addGestureRecognizer:tapGestureRecognizer];
   

    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(16, 14, SCREEN_WIDTH-32, 240)];
    view1.backgroundColor = [UIColor whiteColor];
    view1.layer.cornerRadius = 10;
    view1.clipsToBounds = YES;
    [self.scrollView addSubview:view1];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"推流地址：";
    label.textColor = rgba(153, 153, 153, 1.0);
    label.font = [UIFont systemFontOfSize:12];
    [view1 addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view1).offset(16);
        make.top.mas_equalTo(view1).offset(16);
    }];
    UIButton *scanBtn = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"saoma_img"] title:@"扫码获取" font:[UIFont systemFontOfSize:16] backColot:[UIColor clearColor] textColor:rgba(0, 145, 255, 1) target:self action:@selector(scanBtnAction:) layer:0];
    [scanBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:5];
    [view1 addSubview:scanBtn];
    [scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label.mas_right).offset(5);
        make.centerY.mas_equalTo(label);
    }];
    
    self.urlText = [[UITextField alloc] init];
    self.urlText.placeholder = @"请输入推流地址或扫码获取";
    self.urlText.font = [UIFont systemFontOfSize:14];
    self.urlText.backgroundColor = [UIColor colorWithRed:246/255.0 green:247/255.0 blue:251/255.0 alpha:1.0];
    self.urlText.leftViewMode=UITextFieldViewModeAlways;
    self.urlText.layer.cornerRadius = 5;
    if (@available(iOS 13.0, *)) {
        self.urlText.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    } else {
        // Fallback on earlier versions
    }
//    self.urlText.text = @"rtmp://pili-publish.saaspro.youinsh.net/youin-saas/live47720?e=1700449787&token=B1J122TiGvCU4aaxaVIReLJIGyQRP4UogjqYYM2Q:Did9o3NPlBQLVKwXz0pMhS2CDJg=";
    self.urlText.leftView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    
    [view1 addSubview:self.urlText];
    [self.urlText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label);
        make.right.mas_equalTo(view1.mas_right).offset(-16);
        make.top.mas_equalTo(label.mas_bottom).offset(6);
        make.height.offset(40);
        
    }];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.text = @"采集方式";
    label2.font = [UIFont systemFontOfSize:12];
    label2.textColor = rgba(153, 153, 153, 1.0);
    [view1 addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view1).offset(16);
        make.top.mas_equalTo(self.urlText.mas_bottom).offset(15);
    }];
    
    UILabel *label3 = [[UILabel alloc] init];
    label3.text = @"横屏";
    label3.font = [UIFont systemFontOfSize:14];
    label3.textColor = [UIColor blackColor];
    [view1 addSubview:label3];
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view1).offset(16);
        make.top.mas_equalTo(label2.mas_bottom).offset(10);
    }];
    
    
    UILabel *label4 = [[UILabel alloc] init];
    label4.text = @"画面质量";
    label4.font = [UIFont systemFontOfSize:12];
    label4.textColor = rgba(153, 153, 153, 1.0);
    [view1 addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view1).offset(16);
        make.top.mas_equalTo(label3.mas_bottom).offset(15);
    }];
    
    // 创建 UISegmentedControl
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"流畅",@"标清", @"高清", @"自定义"]];
    self.segmentedControl.selectedSegmentIndex = 2;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    // 添加到视图中
    [view1 addSubview:self.segmentedControl];
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label3);
        make.top.mas_equalTo(label4.mas_bottom).offset(10);
        make.width.offset(240);
        make.height.offset(32);

    }];
    
    
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(16, 28+240, SCREEN_WIDTH-32, 240)];
    view2.backgroundColor = [UIColor whiteColor];
    view2.layer.cornerRadius = 10;
    view2.clipsToBounds = YES;
    [self.scrollView addSubview:view2];
    
    
    //开播
    UIButton *startLive = [UIButton buttonWithType:UIButtonTypeCustom];
    [startLive setBackgroundImage:[UIImage imageNamed:@"kaibo_h"] forState:UIControlStateNormal];
    [startLive setTitle:@"进入直播" forState:UIControlStateNormal];
    [startLive setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    startLive.titleLabel.font = [UIFont systemFontOfSize:18];
    [startLive addTarget:self action:@selector(startLiveAction) forControlEvents:UIControlEventTouchUpInside];
    [view2 addSubview:startLive];
    [startLive mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(130);
        make.centerX.centerY.mas_equalTo(view2);
    }];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.urlText resignFirstResponder];
}

#pragma mark - 清晰度选项卡
- (void)segmentedControlValueChanged:(UISegmentedControl *)segmentedControl
{
    selectedIndex = segmentedControl.selectedSegmentIndex;
    if (selectedIndex == 3) {
        CustomQualityView *qualityView = [[CustomQualityView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/2)];
        qualityView.delegate = self;
        [qualityView show];
    }
}

#pragma mark - 自定义-视频清晰度设置
- (void)qualityDelegateWithWidth:(NSInteger)width withHeight:(NSInteger)height withKbps:(NSInteger)kbps
{
    if (width>0&&height>0&&kbps>0) {
        _videoW = width;
        _videoH = height;
        _videoKb = kbps;
    }else{
        self.segmentedControl.selectedSegmentIndex = 2;
    }
    
}
#pragma mark - 扫码
- (void)QRCodeDelegateWithRTMP:(NSString *)rtmp
{
    self.rtmpStr = rtmp;
    self.urlText.text = rtmp;
}
#pragma mark - 开始直播
- (void)startLiveAction{
    
    if(self.isLiveStoped){
        [[ZXMessageCase shareInstace] showMessage:@"直播已结束"];
        return;
    }
    
    if (self.urlText.text.length==0&&rtmpStr.length==0) {
        [[ZXMessageCase shareInstace] showMessage:@"请输入推流地址"];
        return;
    }
    if(selectedIndex == 3){
        if(_videoH==0||_videoW==0||_videoKb ==0){
            [[ZXMessageCase shareInstace] showMessage:@"自定义请设置视频【宽度】【高度】和【码率】"];
            return;

        }
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
    
    //登录
    __weak typeof(self) weakSelf = self;
    [[YouinRTCManager shardManager] loginIn:userInfo[@"username"] password:userInfo[@"password"] callback:^(NSDictionary *success, NSError * _Nullable error) {
        LandscapeLiveVC *liveVC = [[LandscapeLiveVC alloc] init];
        liveVC.delegate = self;
        liveVC.publishUrl = weakSelf.rtmpStr.length!=0?weakSelf.rtmpStr:self.urlText.text;
        liveVC.quality = self->selectedIndex;
        liveVC.videoWidth = self->_videoW;
        liveVC.videoHeight = self->_videoH;
        liveVC.videoKb = self->_videoKb;
        [weakSelf.navigationController pushViewController:liveVC animated:YES];
    }];
   
}

- (void)LandscapeLiveIsStoped:(BOOL)isStoped
{
    self.isLiveStoped = false;
    if(isStoped){
        self.isLiveStoped = true;
    }
}

- (void)scanBtnAction:(UIButton *)sender
{
    SGAuthorization *authorization = [SGAuthorization authorization];
    [authorization AVAuthorizationBlock:^(SGAuthorization * _Nonnull authorization, SGAuthorizationStatus status) {
        if (status == SGAuthorizationStatusSuccess) {
            QRCodeViewController *WCVC = [[QRCodeViewController alloc] init];
            WCVC.delegate = self;
            WCVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:WCVC animated:YES];
        } else if (status == SGAuthorizationStatusFail) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 有因助手 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alertC animated:YES completion:nil];
            });
        } else {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alertC animated:YES completion:nil];
            });
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
